//
//  AdvisotyDetailViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/20.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON
import Moya
enum PatientCardType: Int {
    /// 自费卡
    case onselfExpense = 1
    /// 医保卡
    case socialSecurity
    /// 双卡
    case double
    
    var description: String {
        switch self {
        case .onselfExpense: return "自费卡"
        case .socialSecurity: return "医保卡"
        case .double: return "有社保"
        }
    }
}

enum YSGDiagnoseType: Int {
    case unknow
    case advisory = 1
    case cloud = 3
    case nurseAdvisory = 4
}

struct AdvisoryDetail: HandyJSON {
    struct AdvisoryDetailImage: HandyJSON {
        var resourceId: String?
        var thumbnailUrl: String?
        var url: String?
        var ext: String?
    }
    
    var patientId: String?
    var patientName: String?
    var patientSex: String?
    var patientAge: String?
    var resultList: [AdvisoryDetailImage]?
    var oneselfState: String?
    var patientUnreadCount: Int = 0
    
    var flag: Int = -1
    var diagnoseId: String?
    
    var jobTitle: String?
    var patientUserId: String?
    var patientNoMsgId: String?
    var doctorName: String?
    var doctorUnreadCount: Int = 0
    var doctorUserId: String?
    var doctorId: String?
    var doctorPicture: String?
    var doctorNoMsgId: String?
    var patientAvatar: String?
    
    /// 过敏史
    var allergyHistory: String?
    /// 既往史
    var pastHistory: String?
    /// 处方权限 1-有 0-无
    var isPrescription: Int = 0
    
    var createTime: String?
    var acceptTime: String?
    var endTime: String?
    var remainingTime: Int = 0
    var isBindingCard: Int = 0
    /// 1-自费卡 2-社保卡 3-双卡
    var cardType: Int = 0
    
    /// 1-图文咨询 3-云门诊
    var diagType: Int = -1
}

struct AdvisoryDetailViewModel {
    struct AdvisoryDetailImageViewModel {
        let imageModel: AdvisoryDetail.AdvisoryDetailImage
        
        var imageId: String { return imageModel.resourceId ?? "" }
        var thumbnailUrl: String { return imageModel.thumbnailUrl ?? ""}
        var originalUurl: String { return imageModel.url ?? "" }
    }
    
    let detail: AdvisoryDetail
    
    var chatReceiveName: String { return detail.doctorName ?? "" }
    
    var chatSendId: Int { return UserDefaults.userId }
    
    var chatReceiveId: String { return detail.doctorUserId ?? "" }
    
    var diagnoseId: String { return detail.diagnoseId ?? "" }
    
    var messageId: String { return detail.patientNoMsgId ?? "" }
    
    var conditionDesc: String { return detail.oneselfState ?? "" }
    
    var detailImages: [AdvisoryDetail.AdvisoryDetailImage] { return detail.resultList ?? [] }
    
    /// 医生职称
    var doctorOffice: String { return detail.jobTitle ?? "" }
    
    /// 患者姓名
    var patientName: String { return detail.patientName ?? "" }
    /// 患者性别
    var patientSex: String { return detail.patientSex ?? "" }
    /// 患者年龄
    var patientAge: String { return detail.patientAge ?? "" }
    
    /// 过敏史
    var allergyHistory: String { return detail.allergyHistory ?? "" }
    /// 既往史
    var pastHistory: String { return detail.pastHistory ?? "" }
    /// 处方权限 1-有 0-无
    var isPrescription: Int { return detail.isPrescription }
    var prescriptionStr: String {
        return isPrescription == 1 ? "处方" : "非处方"
    }
    var prescriptionColor: UIColor? {
        return isPrescription == 1 ? .main : .textLight
    }
    /// 主述
    var oneselfState: String { return detail.oneselfState ?? "" }
    /// 既往史
    var pastHistory_t: String { return detail.pastHistory ?? "" }
    /// 过敏史
    var allergyHistory_t: String { return detail.allergyHistory ?? "" }
    var isAllergyHistory: Bool { return !allergyHistory_t.isEmpty }
    
    /// 图文咨询状态
    var status: AdvisoryStatus { return AdvisoryStatus(rawValue: detail.flag) ?? .unknow }
    
    var doctorAvatar: String { return detail.doctorPicture ?? "" }
    
    var createTime: String { return detail.createTime ?? "" }
    var acceptTime: String { return detail.acceptTime ?? "" }
    var endTime: String { return detail.endTime ?? "" }
    var remainingTime: Int { return detail.remainingTime }
    
    var isBindingCard: Bool { return detail.isBindingCard == 1 }
    /// 1-自费卡 2-社保卡 3-双卡
    var cardType: PatientCardType { return PatientCardType(rawValue: detail.cardType) ?? .onselfExpense }
    var cardText: String {
        if !isBindingCard {
            return "未绑卡"
        } else {
            return cardType.description
        }
    }
    
    var diagType: YSGDiagnoseType { return YSGDiagnoseType(rawValue: detail.diagType) ?? .unknow }
    
    var numberOfItems: Int { return detailImages.count }
    
    var itemWH: CGFloat { return 66 }//(screenW - 16 * 4) / 3 }
    
    func saveDoctorPic() {
        UserDefaults.saveDoctorPic(detail.doctorPicture ?? "")
    }
    
    var avatar_default: UIImage? {
        if patientSex == "女" {
            return UIImage(named: "avatar_female")
        } else {
            return UIImage(named: "avatar_male")
        }
    }
    
    func viewHeight(isExpand: Bool = false) -> CGFloat {
        let defaultH: CGFloat = 3 * 10 + 2 * 20 + (numberOfItems <= 0 ? 0 : 16)
        if !isExpand {
            return defaultH + 30 + collectionViewH()
        } else {
            let descH = conditionDesc.height(font: .regular(14), width: screenW - 16 * 3 - 56)
            let allergyH = allergyHistory.height(font: .regular(14), width: screenW - 16 * 3 - 56)
            let pastH = pastHistory.height(font: .regular(14), width: screenW - 16 * 3 - 56)
//            return defaultH + descH + (allergyH <= 0 ? 20 : allergyH) + (pastH <= 0 ? 20 : pastH) + collectionViewH(isExpand) + 20
            return defaultH + descH + (allergyH <= 0 ? 20 : allergyH) + (pastH <= 0 ? 20 : pastH) + collectionViewH() + 20
        }
    }
    
    func collectionViewH(_ isExpand: Bool = false) -> CGFloat {
        return numberOfItems <= 0 ? 0 : itemWH
//        if !isExpand {
//            return numberOfItems <= 0 ? 0 : itemWH
//        } else {
//            let row = numberOfItems <= 0 ? 0 : (numberOfItems - 1) / 3 + 1
//            return row <= 0 ? 0 : (itemWH + 10) * CGFloat(row) - 10
//        }
    }
    
    func viewModel(for indexPath: IndexPath) -> AdvisoryDetailImageViewModel {
        return AdvisoryDetailImageViewModel(imageModel: detailImages[indexPath.item])
    }
    
    /// 查看患者自述
    static func getPatientAdvisoryDetail<T: TargetType>(target : T,
                                         success: @escaping (_ model: AdvisoryDetail) -> Void,
                                         failure: @escaping (_ errorMsg: String?) -> Void)
    {


        HttpTool.shared.request(target: target, success: { (json, code) in
            YSGLog("查看患者自述 json: \(json)")
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<AdvisoryDetail>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍候重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
}
